﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Xml;

/// <summary>
/// TemplateOperation 的摘要说明
/// 模版的相关的操作
/// </summary>
public class TemplateOperation
{
    private Dbcom cm;

    public TemplateOperation(Dbcom CM)
    {
        cm = CM;
    }


    /// <summary>
    /// 获得默认的文书模板 
    /// </summary>
    /// <param name="textId">该类型文书Id</param>       
    /// <returns></returns>
    public string GetDefaultTemp(string textId)
    {
        /*
         *获取该份文书的默认模板
         * 新增诊疗组模版：诊疗组默认模版优先级最高
         *首先判断是否有科室默认模板，如果没有的话查看这类文书的全员默认模板，如果再没有的话，那就
         */       
        string content = "";
        //重新获取入院记录中相关值        
        try
        {
            //首先判断是否有诊疗组默认模版
          
                DataSet ds_template = Dbcom.GetDataSet("select tid from t_tempplate a  where a.text_type='" +
                                                       textId + "'  and a.isdefault='Y'");
                string sql = "";
                if (ds_template != null)
                {
                    //有诊疗组默认模版
                    if (ds_template.Tables[0].Rows.Count > 0)
                    {
                        sql = "select b.content from t_tempplate a" +
                                                 " inner join t_tempplate_cont b on a.tid = b.tid " +
                                                 " where a.isdefault='Y' and a.text_type='" + textId + "' ";

                        content = Dbcom.ReadSqlVal(sql, 0, "content");
                        return content;
                    }
                }
            
            ////其次判断科室默认模版
            //string section_Id = CurrentPatient.Section_Id.ToString();//App.UserAccount.CurrentSelectRole.Section_Id; 
            //if (section_Id != null)
            //{
            //    DataSet ds_t_s = Dbcom.GetDataSet("select tid from t_tempplate a inner join T_TEMPPLATE_SECTION c on a.tid=c.template_id where a.text_type='" +
            //        textId + "' and c.section_id='" + section_Id + "' and c.ISDEFAULT='Y'");

            //    string Sql = "";

            //    if (ds_t_s != null)
            //    {
            //        //有科室模板
            //        if (ds_t_s.Tables[0].Rows.Count > 0)
            //        {
            //            Sql = "select b.content from t_tempplate a" +
            //                                      " inner join t_tempplate_cont b on a.tid = b.tid inner join t_tempplate_section c on a.tid=c.template_id " +
            //                                      " where c.isdefault='Y' and a.text_type='" + textId + "' and c.section_id=" + section_Id + "";

            //            content = Dbcom.ReadSqlVal(Sql, 0, "content");
            //        }
            //        else
            //        {
            //            Sql = "select b.content from t_tempplate a" +
            //                  " inner join t_tempplate_cont b on a.tid = b.tid" +
            //                  " where a.isdefault='Y' and a.text_type='" + textId + "' and a.section_id is null";
            //            content = Dbcom.ReadSqlVal(Sql, 0, "content");

            //        }
            //    }
            //}
            return content;
        }
        catch
        {
            return "";
        }
    }


    /// <summary>
    /// 读取默认模版根据TID
    /// </summary>
    /// <param name="tid"></param>
    /// <returns></returns>
    public string GetTemplateByid(string tid)
    {
        try
        {           
            string content=Dbcom.ReadSqlVal("select content from t_tempplate_cont where tid=" + tid + "",0, "content");
            return content;
        }
        catch
        {
            return "";
        }
    }


    /// <summary>
    /// 树形菜单信息加载（文书除外）
    /// </summary>
    /// <param name="trvBook">树形菜单</param>
    public UcTreeNode ReflashTemplateBookTree()
    {
        try
        {       
            UcTreeNode trvBook = new UcTreeNode();          
            string SQl = "select * from T_TEXT where ENABLE_FLAG='Y'";
            DataSet ds = new DataSet();
            ds = Dbcom.GetDataSet(SQl);
            Class_Text[] Directionarys = GetSelectClassDs(ds);
            if (Directionarys != null)
            {
                for (int i = 0; i < Directionarys.Length; i++)
                {
                    if (Directionarys[i].Parentid == 0)
                    {
                        UcTreeNode tn = new UcTreeNode();
                        tn.Tag = Directionarys[i];
                        tn.Text = Directionarys[i].Textname;
                        tn.Name = Directionarys[i].Id.ToString();
                        SetTreeView(Directionarys, tn);
                        trvBook.Childnodes.Add(tn);
                    }
                }
            }         
            return trvBook;
        }
        catch
        {
            return null;
        }
    }


    /// <summary>
    /// 刷新文书操作的树
    /// </summary>
    public UcTreeNode ReflashTemplateTrvBook(string msg)
    {       
        //InPatientInfo inpatient = GetInpatientByBedId();
        Class_Patients[] templates;
        DataSet Temp_Sections;           //获取说有的模板绑定的科室
        DataSet Temp_Groups;             //获取说有的模板绑定的诊疗组

        Temp_Sections = Dbcom.GetDataSet("select * from T_TEMPPLATE_SECTION");//有取所有科室和模板的关系
        Temp_Groups = Dbcom.GetDataSet("select * from T_TEMPPLATE_GROUP");//有取所有诊疗组和模板的关系

        UcTreeNode Node = ReflashTemplateBookTree();


        templates = GetTemplates(msg);
        if (templates != null)  //存在模板
        {
            foreach (Class_Patients template in templates)
            {
                setTreeView3(template, Node.Childnodes, Temp_Groups, Temp_Sections);
            }
        }

        return Node;
    }

    public UcTreeNode ReflashTemplateTrvBookByCheckType(string chkDocType,string rdoPersonal,string rdoSection,string rdoHospital,
        string rdoGroup,string txtDocName,string chkAllDefault,string chkAll,string chkSectionDefault,string chkSection,string chkGroupDefault,
        string chkGroup,string chkPerson)
    {
        string msg = "";
        if (chkDocType== "true")
        {
            //文书类型
            if (rdoPersonal== "true")
            {
                msg += "TEMPPLATE_LEVEL='P' ";
            }
            else if (rdoSection== "true")
            {
                msg += "TEMPPLATE_LEVEL='S' ";
            }
            else if (rdoHospital== "true")
            {
                msg += "TEMPPLATE_LEVEL='H' ";
            }
            else if (rdoGroup== "true")
            {
                msg += "TEMPPLATE_LEVEL='G' ";
            }

            string tname = "";  //模板名称
            if (txtDocName.Trim() != "")
            {
                tname = txtDocName.Trim();
                msg += "and TNAME like '%" + tname + "%' ";
            }
        }
        else
        {
            //使用范围
            if (chkAllDefault== "true")
            {
                //全院默认
                if (msg != "")
                    msg = msg + " or ";
                msg += "(TEMPPLATE_LEVEL='H' and isdefault='Y') ";
            }
            if (chkAll== "true")
            {
                //全院
                if (msg != "")
                    msg = msg + " or ";
                msg += "(TEMPPLATE_LEVEL='H' and  isdefault='N') ";
            }
            if (chkSectionDefault== "true")
            {
                //科室默认
                if (msg != "")
                    msg = msg + " or ";
                msg += "(TEMPPLATE_LEVEL='S' and tid in (select template_id from t_tempplate_section where isdefault='Y')) ";
            }
            if (chkSection== "true")
            {
                //科室
                if (msg != "")
                    msg = msg + " or ";
                msg += "(TEMPPLATE_LEVEL='S' and tid not in (select template_id from t_tempplate_section where isdefault='Y')) ";
            }
            if (chkGroupDefault== "true")
            {
                //诊疗组默认
                if (msg != "")
                    msg = msg + " or ";
                msg += "tid in (select template_id from t_tempplate_group where isdefault='Y') ";
            }
            if (chkGroup== "true")
            {
                //诊疗组
                if (msg != "")
                    msg = msg + " or ";
                msg += "tid in (select template_id from t_tempplate_group) ";
            }
            if (chkPerson== "true")
            {
                //个人
                if (msg != "")
                    msg = msg + " or ";
                msg += "TEMPPLATE_LEVEL='P' ";
            }
        }
        return ReflashTemplateTrvBook(msg);
    }

    public string GetNodeColor(Class_Patients templates)
    {
        if (templates != null)
        {          
            DataSet Temp_Sections;           //获取说有的模板绑定的科室
            DataSet Temp_Groups;             //获取说有的模板绑定的诊疗组

            Temp_Sections = Dbcom.GetDataSet("select * from T_TEMPPLATE_SECTION");//有取所有科室和模板的关系
            Temp_Groups = Dbcom.GetDataSet("select * from T_TEMPPLATE_GROUP");//有取所有诊疗组和模板的关系


            //if (templates.Default_sec_id != "" && templates.Section_ID.ToString() != "" && templates.IsDefault == 'Y')
            if (Temp_Groups.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0)
            {
                //诊疗组级的默认模板
                return ColorTranslator.ToHtml(Color.Teal);
            }
            else if (Temp_Sections.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0)
            {
                //科室级默认模板
                return ColorTranslator.ToHtml(Color.Blue);
            }
            else if (templates.TempPlate_Level == 'H' && templates.IsDefault == 'Y')
            {
                //全院默认模板
                return Color.Green.ToString();
            }
            else if (Temp_Groups.Tables[0].Select("ISDEFAULT='N' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0 &&
                     Temp_Groups.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length == 0)
            {
                //诊疗模板
                return ColorTranslator.ToHtml(Color.DarkSlateBlue);
            }
            else if (Temp_Sections.Tables[0].Select("ISDEFAULT='N' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0 &&
                     Temp_Sections.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length == 0)
            {
                //科室模板
                return ColorTranslator.ToHtml(Color.Crimson);
            }
            else if (templates.TempPlate_Level == 'H' && templates.IsDefault == 'N')
            {
                //全院默认模板
                return ColorTranslator.ToHtml(Color.DarkGoldenrod);
            }
            else
            {
                //什么都不是
                return ColorTranslator.ToHtml(Color.Black);
            }

        }
        return ColorTranslator.ToHtml(Color.Black);
    }



    /// <summary>
    /// 添加新模版
    /// </summary>
    /// <param name="sick_Id"></param>
    /// <param name="agestyle"></param>
    /// <param name="cpd"></param>
    /// <param name="ISDEFAULT"></param>
    /// <param name="TextKind"></param>
    /// <param name="Role_type"></param>
    /// <param name="xmldocstr"></param>
    /// <returns></returns>
    public int AddNewTemplate(string sick_Id, string agestyle, string ages,
        string TName,string Shortcut, string TempPlate_Level, string Sex, string SickArea_ID,
        string Creator_ID, string Create_Time, string Updater_ID, string Update_Time,
        string Verify_ID1, string Verify_Time1,
        string Verify_ID2, string Verify_Time2,
        string Verify_Sign, string Section_ID,
        string ISDEFAULT, string TextKind, string Role_type, string xmldocstr)
    {        
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(xmldocstr);      
        int resault = 0;
        #region 添加模版
        //模版Id
        string Tid = Dbcom.GenId().ToString();
        int Ages = Convert.ToInt32(ages);
        //年龄段
        if (agestyle == "rdoAgeNull")
        {
            Ages = -1;
        }
        else if (agestyle == "rdoEnfant")
        {
            Ages = Convert.ToInt32(Dbcom.GetDataSet("select ID from t_data_code where Name='儿童'").Tables[0].Rows[0]["ID"]);
        }
        else if (agestyle == "rdoLad")
        {
            Ages = Convert.ToInt32(Dbcom.GetDataSet("select ID from t_data_code where Name='少年'").Tables[0].Rows[0]["ID"]);
        }
        else if (agestyle == "rdoYouth")
        {
            Ages = Convert.ToInt32(Dbcom.GetDataSet("select ID from t_data_code where Name='青年'").Tables[0].Rows[0]["ID"]);
        }
        else if (agestyle == "rdoMiddle")
        {
            Ages = Convert.ToInt32(Dbcom.GetDataSet("select ID from t_data_code where Name='中年'").Tables[0].Rows[0]["ID"]);
        }
        else if (agestyle == "rdoOld")
        {
            Ages = Convert.ToInt32(Dbcom.GetDataSet("select ID from t_data_code where Name='老年'").Tables[0].Rows[0]["ID"]);
        }
        ArrayList Sqls = new ArrayList();
        //设置默认模板
        if (ISDEFAULT == "Y")
        {
            Sqls.Add("update T_TempPlate set ISDEFAULT='N' where text_type='" + TextKind + "'");
        }
        //设置是更新或者新增
        string temp = "";
        if (TextKind != "")
        {
            DataSet samedocs = Dbcom.GetDataSet("select tid from T_TempPlate where tname='" +TName + "' and tid='" + TextKind + "'");
            if (samedocs.Tables[0] != null)
            {
                if (samedocs.Tables[0].Rows.Count > 0)
                {
                    //App.MsgWaring("已经存在相同名称的文书，请先修改名称");
                    return -1;
                }
            }

        }
        else
        {
            string sql = "select * from T_TempPlate where tname='" + TName + "' and sick_Id='" + sick_Id + "'";
            DataSet ds = Dbcom.GetDataSet(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                //App.Msg("此模板已经存在，请更换其它模板名！");
                return -2;
            }
        }
        
        temp = "insert into T_TempPlate(tid, tname, shortcut, text_type, tempplate_level, sex, ages, sickarea_id, creator_id, create_time, updater_id, update_time, verify_id1, verify_time1, verify_id2, verify_time2, verify_sign, isdiag, enable_flag,ISDEFAULT,SICK_ID) values(" + Tid + ",'" + TName + "','" + Shortcut + "',"
                                            + "'" + TextKind + "','" + TempPlate_Level + "','" + Sex + "'," + Ages + ","
                                            + SickArea_ID + "," + Creator_ID + ",to_timestamp("
                                            + " '" + Create_Time + "','yyyy-MM-dd HH24:mi')," + Updater_ID + ",'" + Update_Time + "'," + Verify_ID1 + ","
                                            + "'" + Verify_Time1 + "'," + Verify_ID2 + ",'" + Verify_Time2 + "','" + Verify_Sign + "',"
                                            + "'N','N','" + ISDEFAULT + "','" + sick_Id + "')";
        Sqls.Add(temp);
        if (Role_type == "D")
        {
            //科室医生保存模板
            if (TempPlate_Level == "S")
            {
                Sqls.Add("insert into T_TEMPPLATE_SECTION(TEMPLATE_ID,SECTION_ID,ISDEFAULT)values(" + Tid + ",'" + Section_ID + "','N')");
            }
        }


        /*
         * 移除含有timeTitle属性的div节点
         */
        XmlNode root = xmldoc.FirstChild;
        bool atrribue = false;
        foreach (XmlNode firstNode in root.ChildNodes)
        {
            if (firstNode.Name == "body")
            {
                foreach (XmlNode secondNode in firstNode.ChildNodes)
                {
                    if (secondNode.Name == "div")
                    {
                        if (secondNode != null)
                        {
                            for (int i = 0; i < secondNode.Attributes.Count; i++)
                            {
                                if (secondNode.Attributes[i].Name.Trim().ToLower() == "timetitle")
                                    atrribue = true;
                            }

                            if (atrribue)
                            {
                                firstNode.RemoveChild(secondNode);
                                break;
                            }
                        }
                    }
                }
            }
            if (atrribue)
                break;
        }

        int message = 0;
        string divTitle = "test";
        //插入标签模块
        string insertLable = "insert into T_TempPlate_Cont(ID,TID,LableName,Content)values(" + Tid + "," + Tid + ",'" + divTitle + "',:divContent)";
        DBParameter[] xmlPars = new DBParameter[1];
        xmlPars[0] = new DBParameter();
        xmlPars[0].ParameterName = "divContent";
        //xmlPars[0].Value = divNode.OuterXml;
        xmlPars[0].Value = xmldoc.OuterXml;
        xmlPars[0].DBType = Oracle.ManagedDataAccess.Client.OracleDbType.Clob;
        xmlPars[0].Direction = ParameterDirection.Input;
        message = Dbcom.ExecuteSQLWithParams(insertLable, xmlPars);

        if (message > 0)
        {
            string[] AddSqls = new string[Sqls.Count];

            for (int i = 0; i < Sqls.Count; i++)
            {
                AddSqls[i] = Sqls[i].ToString();
            }

            resault = Dbcom.ExecuteBatch(AddSqls);
        }
        return resault;
        #endregion
    }

    /// <summary>
    /// 保存模版
    /// </summary>
    /// <param name="current_id"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    public int UpdateTemplate(string current_id, string content)
    {               
        int message = 0;       
        string filterKetWord = "select Source_word,Target_word from T_TempPlate_Filter where Enable_Flag='Y'";
        DataSet filterKetWordDS = Dbcom.GetDataSet(filterKetWord);
        ArrayList source_words = new ArrayList();
        ArrayList target_words = new ArrayList();
        if (filterKetWordDS != null)
        {
            DataTable dataTable = filterKetWordDS.Tables[0];

            string source_word = "";
            string target_word = "";
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                source_word = dataTable.Rows[i]["source_word"].ToString();
                source_words.Add(source_word);
                target_word = dataTable.Rows[i]["target_word"].ToString();
                target_words.Add(target_word);
            }

            content = IsFilter(content, source_words);//过滤关键字
        }
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.LoadXml(content);
        string updateLable = "update T_TempPlate_Cont set Content=:divContent where tid=" + current_id;
        DBParameter[] xmlPars = new DBParameter[1];
        xmlPars[0] = new DBParameter();
        xmlPars[0].ParameterName = "divContent";
        //xmlPars[0].Value = divNode.OuterXml;
        xmlPars[0].Value = content;//bodyNode.InnerXml;
        xmlPars[0].DBType =Oracle.ManagedDataAccess.Client.OracleDbType.Clob;
        xmlPars[0].Direction = ParameterDirection.Input;
        message = Dbcom.ExecuteSQLWithParams(updateLable, xmlPars);
        return message;
    }

    /// <summary>
    /// 删除模版
    /// </summary>
    /// <param name="tid"></param>
    /// <returns></returns>
    public int DeleteTemplate(string tid)
    {       
        string delPatients_Doc = "delete from t_tempplate where tid=" + tid;
        string delModel_Lable = "delete from t_tempplate_cont where tid=" + tid;
        string[] strSqls = { delPatients_Doc, delModel_Lable };
        int i = Dbcom.ExecuteBatch(strSqls);
        return i;
    }


    /// <summary>
    /// 判断模版默认情况
    /// </summary>
    /// <param name="tid"></param>
    /// <param name="isdefault"></param>
    /// <param name="default_sec"></param>
    public void IsDefualtTemplate(string tid,ref string isdefault,ref string default_sec)
    {       
        string sql = "select ISDEFAULT,DEFAULT_SEC_ID from T_TempPlate where tid=" + tid;
        isdefault = Dbcom.ReadSqlVal(sql, 0, "ISDEFAULT");
        default_sec= Dbcom.ReadSqlVal(sql, 0, "DEFAULT_SEC_ID");
        if (default_sec != "")
        {
            default_sec = "Y";
        }
        else
        {
            default_sec = "N";
        }

    }

    /// <summary>
    /// 设置全院默认模版    
    /// </summary>
    /// <param name="tid"></param>
    /// <param name="parentid"></param>
    /// <returns></returns>
    public int SetHospiltalDefaultTemplate(string tid,string parentid,ref string oldId)
    {     
        int resalut=0;
        string[] sqls = new string[3];
        //取消老模板
        string oldSql = "select * from T_TempPlate where TEXT_TYPE='" + parentid + "' and ISDEFAULT='Y' and DEFAULT_SEC_ID is null and SECTION_ID is null";
        oldId = Dbcom.ReadSqlVal(oldSql, 0, "TID");


        //默认模板的取消
        sqls[0] = "update T_TempPlate set ISDEFAULT='N',DEFAULT_SEC_Id=null,SECTION_ID=null where DEFAULT_SEC_ID is null and TEXT_TYPE='" + parentid + "' and SECTION_ID is null and ISDEFAULT='Y'";

        //设置默认模板
        sqls[1] = "update T_TempPlate set tempplate_level='H',ISDEFAULT='Y',DEFAULT_SEC_Id=null,SECTION_ID=null where tid =" + tid;

        //删除所有的科室模板设置
        sqls[2] = "delete from t_tempplate_section t where TEMPLATE_ID=" + tid+ "";
        resalut = Dbcom.ExecuteBatch(sqls);
        return resalut;
    }

    /// <summary>
    /// 设置为全院模版
    /// </summary>
    /// <param name="tid"></param>
    /// <param name="parentid"></param>
    /// <param name="oldId"></param>
    /// <returns></returns>
    public int SetHospiltalTemplate(string tid, string parentid, ref string oldId)
    {       
        int resalut = 0;
        string[] sqls = new string[2];
        //取消老模板
        string oldSql = "select * from T_TempPlate where TEXT_TYPE='" + resalut + "' and ISDEFAULT='Y' and DEFAULT_SEC_ID is null and SECTION_ID is null";
        oldId = Dbcom.ReadSqlVal(oldSql, 0, "TID");


        //设置默认模板
        sqls[0] = "update T_TempPlate set tempplate_level='H',ISDEFAULT='N',DEFAULT_SEC_Id=null,SECTION_ID=null where tid =" + tid;

        //删除所有的科室模板设置
        sqls[1] = "delete from t_tempplate_section t where TEMPLATE_ID=" + tid + "";
        resalut = Dbcom.ExecuteBatch(sqls);

        return resalut;

    }


    /// <summary>
    /// 过滤关键字
    /// </summary>
    /// <param name="source">需要过滤的源文件，即需要保存的编辑器中生成的XMl串</param>
    /// <param name="filter">关键字</param>
    /// <returns></returns>
    public string IsFilter(string source, ArrayList filter)
    {
        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.LoadXml(source);
        try
        {

            XmlElement rootElement = doc.DocumentElement;
            XmlNodeList list = doc.GetElementsByTagName("select");


            //获取下拉知识库结点 过滤关键字
            for (int i = 0; i < filter.Count; i++)
            {

                for (int j = 0; j < list.Count; j++)
                {
                    if (list[j].Name == "select")
                    {
                        // keys[i] = list[i].Attributes["value"].Value;
                        if (list[j].Attributes["text"].Value.Trim() == filter[i].ToString().Trim())
                        {
                            //list[j].Attributes["forecolor"].Value = "#FF0000";
                            list[j].Attributes["value"].Value = list[j].Attributes["name"].Value;
                            list[j].Attributes["text"].Value = list[j].Attributes["name"].Value;
                        }
                    }
                }
            }
            source = doc.OuterXml;

            //遍历<span>中的文字,把相应的文字过滤，并设置文本显示前景色
            list = doc.GetElementsByTagName("span");
            for (int i = 0; i < filter.Count; i++)
            {
                for (int j = 0; j < list.Count; j++)
                {
                    if (list[j].Name == "span")
                    {

                        //测试
                        //ArrayList arry = getIndex(list[j].InnerText, filter[i].ToString());
                        //ArrayList test = new ArrayList();
                        //string temp = "";
                        //for (int k = 1; k <= arry.Count; k++)
                        //{
                        //    temp = list[j].InnerText.Substring((int)arry[k - 1], filter[i].ToString().Length);//(int)arry[k]-(int)arry[k-1]);
                        //    test.Add(temp);
                        //}
                        //因为如果两个需要过滤的关键字是相邻的，那么在编辑器中是作为同一个<span>标签的InnerText处理的，
                        //所以在过滤<span>中的关键字时候需要判断<span>的InnerText中是否包含关键字，如果包含的话把关键字
                        //过滤，然后把前景色改为#FF0000
                        if (list[j].InnerText.IndexOf(filter[i].ToString()) > -1)
                        {                 


                            list[j].InnerText = list[j].InnerText.Replace(filter[i].ToString().Trim(), filter[i].ToString());
                            if (list[j].Attributes["forecolor"] != null)
                                list[j].Attributes["forecolor"].Value = "#FF0000";
                        }
                    }
                }
            }
            source = doc.OuterXml;
            return source;
        }
        catch
        {
            return doc.OuterXml;
        }
    }


    /// <summary>
    /// 获取模版集合
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="GStyle"></param>
    /// <param name="Kindtid"></param>
    /// <param name="section_id"></param>
    /// <returns></returns>
    public DataSet GetTemplateByCondition(string msg, string GStyle,string Kindtid,string section_id)
    {
        try
        {          
            DataSet ds = new DataSet();
            string Sql = "select distinct t.Tid,t.tname as 模板名称,t.create_time as 创建时间,t.TEMPPLATE_LEVEL as 模板级别 from t_tempplate t inner join t_sick_type s on t.sick_id=s.id ";
            if (GStyle == "G")
                Sql = "select distinct t.Tid,t.tname as 模板名称,t.create_time as 创建时间,t.TEMPPLATE_LEVEL as 模板级别 from t_tempplate t inner join t_sick_type s on t.sick_id=s.id inner join T_TEMPPLATE_GROUP c on t.tid=c.template_id";
            else if (GStyle == "S")
                Sql = "select distinct t.Tid,t.tname as 模板名称,t.create_time as 创建时间,t.TEMPPLATE_LEVEL as 模板级别 from t_tempplate t inner join t_sick_type s on t.sick_id=s.id inner join T_TEMPPLATE_SECTION c on t.tid=c.template_id ";

            if (msg == "")
            {
                ds.Clear();
                string tempSql = Sql + " where t.text_type='" + Kindtid + "' and t.tempplate_level='S' and t.SECTION_ID='" + section_id + "'";
                ds = Dbcom.GetDataSet(tempSql);
            }
            else
            {
                ds.Clear();
                string tempSql = Sql + " where text_type='" + Kindtid + "'" + msg;
                ds = Dbcom.GetDataSet(tempSql);
            }
            return ds;
        }
        catch
        {
            return null;
        }
    }


    /// <summary>
    /// 获取文书大类子类的排序集合
    /// </summary>
    /// <param name="parentid"></param>
    /// <returns></returns>
    public DataSet GetTemplateChildNodesOrder(string parentid)
    {      
        string sql = "select id,textname,PRINTORDER,(case when ISNEWPAGE='Y' then '是' else '否' end) ISNEWPAGE from T_TEXT where PARENTID=" + parentid + " order by PRINTORDER,id ";
        return Dbcom.GetDataSet(sql);
    }

    /// <summary>
    /// 设置
    /// </summary>
    /// <param name="autotype"></param>
    /// <param name="conditons"></param>
    /// <returns></returns>
    public int SetTemplateChildNodesOrder(string autotype, List<string> conditons)
    {       
        List<string> sqls = new List<string>();
        if (autotype == "ture")
        {
            //自动排序集合
            for (int i = 0; i < conditons.Count; i++)
            {
                string ordernum = conditons[i].Split(',')[0].ToString();
                string templateid = conditons[i].Split(',')[1].ToString();
                sqls.Add("update t_text set PRINTORDER=" + ordernum + " where ID=" + templateid + "");
               
            }
        }
        else
        {
            //手动排序集合

            for (int i = 0; i < conditons.Count; i++)
            {
                string ordernum = conditons[i].Split(',')[0].ToString();
                string isnewpage = conditons[i].Split(',')[1].ToString();
                string templateid = conditons[i].Split(',')[2].ToString();
               
                sqls.Add("update t_text set PRINTORDER=" + ordernum + ",ISNEWPAGE=" + isnewpage + " where ID=" +
                      templateid + "");

            }
           
        }
        return Dbcom.ExecuteBatch(sqls.ToArray());
    }

    #region 私有函数
    /// <summary>
    /// 实例化查询结果 Class_Template
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    private Class_Patients[] GetTemplates(string msg)
    {      
        string sql = "";
        if (msg != "")
        {
            sql = "select * from t_tempplate where " + msg;// where Text_type = " + textId;
        }
        else
        {
            sql = "select * from t_tempplate";// where Text_type = " + textId;
        }
        DataSet ds = Dbcom.GetDataSet(sql);        

        if (ds != null)
        {
            Class_Patients[] templates = new Class_Patients[ds.Tables[0].Rows.Count];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                templates[i] = new Class_Patients();
                templates[i].Tid = Convert.ToInt32(ds.Tables[0].Rows[i]["TID"]);
                templates[i].TName = ds.Tables[0].Rows[i]["TNAME"].ToString();
                if (ds.Tables[0].Rows[i]["TEXT_TYPE"].ToString().Trim() != "")
                    templates[i].TextKind = ds.Tables[0].Rows[i]["TEXT_TYPE"].ToString();
                if (ds.Tables[0].Rows[i]["TEMPPLATE_LEVEL"].ToString().Trim() != "")
                    templates[i].TempPlate_Level = Convert.ToChar(ds.Tables[0].Rows[i]["TEMPPLATE_LEVEL"]);
                if (ds.Tables[0].Rows[i]["ISDEFAULT"].ToString().Trim() != "")
                    templates[i].IsDefault = Convert.ToChar(ds.Tables[0].Rows[i]["ISDEFAULT"]);
                templates[i].Default_sec_id = ds.Tables[0].Rows[i]["DEFAULT_SEC_ID"].ToString();           
            }
            return templates;
        }
        else
        {
            return null;
        }
    }

    
    /// <summary>
    /// 对文书进行分类设置
    /// </summary>
    /// <param Name="Directionarys">所有文书节点集合</param>
    /// <param Name="currentnode">当前文书节点</param>
    private void SetTreeView(Class_Text[] Directionarys, UcTreeNode current)
    {
        for (int i = 0; i < Directionarys.Length; i++)
        {
            Class_Text cunrrentDir = (Class_Text)current.Tag;
            if (Directionarys[i].Parentid == cunrrentDir.Id)
            {
                UcTreeNode tn = new UcTreeNode();
                tn.Tag = Directionarys[i];
                tn.Text = Directionarys[i].Textname;
                tn.Name = Directionarys[i].Id.ToString();
                tn.Imageindex = 9;
                tn.Selectimageindex = 9;
                current.Childnodes.Add(tn);
                SetTreeView(Directionarys, tn);
            }
        }
    }

    /// <summary>
    /// 实例化查询结果
    /// </summary>
    /// <param Name="tempds"></param>
    /// <returns></returns>
    private Class_Datacodecs[] GetSelectDirectionary(DataSet tempds)
    {
        if (tempds != null)
        {
            if (tempds.Tables[0].Rows.Count > 0)
            {
                Class_Datacodecs[] Directionary = new Class_Datacodecs[tempds.Tables[0].Rows.Count];
                for (int i = 0; i < tempds.Tables[0].Rows.Count; i++)
                {
                    Directionary[i] = new Class_Datacodecs();
                    Directionary[i].Id = tempds.Tables[0].Rows[i]["ID"].ToString();
                    Directionary[i].Name = tempds.Tables[0].Rows[i]["NAME"].ToString();
                    Directionary[i].Code = tempds.Tables[0].Rows[i]["CODE"].ToString();
                    Directionary[i].Shortchut_code = tempds.Tables[0].Rows[i]["SHORTCUT_CODE"].ToString();
                    Directionary[i].Enable = tempds.Tables[0].Rows[i]["ENABLE"].ToString();
                    Directionary[i].Type = tempds.Tables[0].Rows[i]["TYPE"].ToString();
                }
                return Directionary;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// 实例Class_Text化查询结果
    /// </summary>
    /// <param Name="tempds"></param>
    /// <returns></returns>
    private  Class_Text[] GetSelectClassDs(DataSet tempds)
    {
        if (tempds != null)
        {
            if (tempds.Tables[0].Rows.Count > 0)
            {
                Class_Text[] class_text = new Class_Text[tempds.Tables[0].Rows.Count];
                for (int i = 0; i < tempds.Tables[0].Rows.Count; i++)
                {
                    class_text[i] = new Class_Text();
                    class_text[i].Id = Convert.ToInt32(tempds.Tables[0].Rows[i]["ID"].ToString());
                    if (tempds.Tables[0].Rows[i]["PARENTID"].ToString() != "0")
                    {
                        class_text[i].Parentid = Convert.ToInt32(tempds.Tables[0].Rows[i]["PARENTID"].ToString());
                    }
                    class_text[i].Textcode = tempds.Tables[0].Rows[i]["TEXTCODE"].ToString(); ;
                    class_text[i].Textname = tempds.Tables[0].Rows[i]["TEXTNAME"].ToString();
                    class_text[i].Isenable = tempds.Tables[0].Rows[i]["ISENABLE"].ToString();
                    class_text[i].Txxttype = tempds.Tables[0].Rows[i]["ISBELONGTOTYPE"].ToString();
                }
                return class_text;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    private void setTreeView2(Class_Patients templates, List<UcTreeNode> nodes, DataSet Temp_Groups, DataSet Temp_Sections)
    {
        if (templates != null)
        {
            foreach (UcTreeNode node in nodes)
            {
                if (node.Tag.GetType().ToString().Contains("Class_Text"))
                {
                    Class_Text cunrrentDir = node.Tag as Class_Text;
                    if (templates.TextKind == cunrrentDir.Id.ToString())
                    {
                        UcTreeNode tn = new UcTreeNode();
                        if (Temp_Groups.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0)
                        {
                            //诊疗组级的默认模板
                            tn.ForeColor = Color.Teal.ToString();
                        }
                        else if (Temp_Sections.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0)
                        {
                            //科室级默认模板
                            tn.ForeColor = Color.Blue.ToString();
                        }
                        else if (templates.TempPlate_Level == 'H' && templates.IsDefault == 'Y')
                        {
                            //全院默认模板
                            tn.ForeColor = Color.Green.ToString();
                        }
                        else if (Temp_Groups.Tables[0].Select("ISDEFAULT='N' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0 &&
                                 Temp_Groups.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length == 0)
                        {
                            //诊疗模板
                            tn.ForeColor = Color.DarkSlateBlue.ToString();
                        }
                        else if (Temp_Sections.Tables[0].Select("ISDEFAULT='N' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0 &&
                                 Temp_Sections.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length == 0)
                        {
                            //科室模板
                            tn.ForeColor = Color.Crimson.ToString();
                        }
                        else if (templates.TempPlate_Level == 'H' && templates.IsDefault == 'N')
                        {
                            //全院默认模板
                            tn.ForeColor = Color.DarkGoldenrod.ToString();
                        }
                        else
                        {
                            //什么都不是
                            tn.ForeColor = Color.Black.ToString();
                        }

                        tn.Tag = templates;
                        tn.Text = templates.TName;
                        tn.Name = templates.Tid.ToString();
                        tn.Imageindex = 13;
                        tn.Selectimageindex = 13;
                        node.Childnodes.Add(tn);
                        node.Selectimageindex = 6;
                        node.Imageindex = 6;
                    }
                }

                if (node.Childnodes.Count > 0)
                    setTreeView2(templates, node.Childnodes, Temp_Groups, Temp_Sections);

            }
        }
    }

    private void setTreeView3(Class_Patients templates, List<UcTreeNode> nodes, DataSet Temp_Groups, DataSet Temp_Sections)
    {
        if (templates != null)
        {
            foreach (UcTreeNode node in nodes)
            {
                if (node.Tag.GetType().ToString().Contains("Class_Text"))
                {
                    Class_Text cunrrentDir = node.Tag as Class_Text;
                    if (templates.TextKind == cunrrentDir.Id.ToString())
                    {
                        UcTreeNode tn = new UcTreeNode();
                        //if (templates.Default_sec_id != "" && templates.Section_ID.ToString() != "" && templates.IsDefault == 'Y')
                        if (Temp_Groups.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + 
                            templates.Tid.ToString() + "'").Length > 0)
                        {
                            //诊疗组级的默认模板
                            tn.ForeColor = Color.Teal.ToString();
                        }
                        else if (Temp_Sections.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + 
                            templates.Tid.ToString() + "'").Length > 0)
                        {
                            //科室级默认模板
                            tn.ForeColor = Color.Blue.ToString();
                        }
                        else if (templates.TempPlate_Level == 'H' && templates.IsDefault == 'Y')
                        {
                            //全院默认模板
                            tn.ForeColor = Color.Green.ToString();
                        }
                        else if (Temp_Groups.Tables[0].Select("ISDEFAULT='N' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0 &&
                                 Temp_Groups.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length == 0)
                        {
                            //诊疗模板
                            tn.ForeColor = Color.DarkSlateBlue.ToString();
                        }
                        else if (Temp_Sections.Tables[0].Select("ISDEFAULT='N' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length > 0 &&
                                 Temp_Sections.Tables[0].Select("ISDEFAULT='Y' and TEMPLATE_ID='" + templates.Tid.ToString() + "'").Length == 0)
                        {
                            //科室模板
                            tn.ForeColor = Color.Crimson.ToString();
                        }
                        else if (templates.TempPlate_Level == 'H' && templates.IsDefault == 'N')
                        {
                            //全院默认模板
                            tn.ForeColor = Color.DarkGoldenrod.ToString();
                        }
                        else
                        {
                            //什么都不是
                            tn.ForeColor = Color.Black.ToString();
                        }
                        tn.Tag = templates;
                        tn.Text = templates.TName;
                        tn.Name = templates.Tid.ToString();
                        tn.Imageindex = 13;
                        tn.Selectimageindex = 13;
                        node.Childnodes.Add(tn);
                        node.Selectimageindex = 6;
                        node.Imageindex = 6;
                        //SetParentNodeExpand(tn);

                    }
                }

                if (node.Childnodes.Count > 0)
                    setTreeView3(templates, node.Childnodes, Temp_Groups, Temp_Sections);

            }
        }
    } 

    #endregion


}